<template>
<div>
    <div class='search'>
        <input 
        class='search-input' 
        type="text" 
        placeholder="请输入城市名字/拼音"
        v-model='keyword'
        >
    </div>
    <div class="search-content" v-show="keyword" ref='searchContent'>
        <ul>
            <li 
             class="search-item border-bottom" 
             v-for="item in list"
             :key="item.id"
             @click="handleCityClick(item.name)"
            >
            {{item.name}}
            </li>
            <li class="search-item border-bottom" v-show="hasNoData">未找到匹配项</li>
        </ul>
    </div>
</div>
</template>
<script>
import {mapMutations} from "vuex"
import BScroll from "better-scroll"
export default {
  name:"CitySearch",
  props:{
    cities:Object
  },
  data (){
    return {
        keyword:"",
        timer:null,
        list:[]
    }
  },
  computed:{
     hasNoData (){
         return !this.list.length
     }
  },
  watch:{
     keyword (){
         if(this.timer){
             clearTimeout(this.timer)
         }
         if(!this.keyword){
             this.list=[]
         }
         this.timer=setTimeout(()=>{
            const result=[];
            for (let i in this.cities){
                this.cities[i].forEach((value)=>{
                    if(value.name.indexOf(this.keyword)>-1 ||
                    value.spell.indexOf(this.keyword)>-1){
                        result.push(value)
                    }
                })
            }
            this.list=result
         },100)
     }
  },
  methods:{
     handleCityClick (city){
         this.changeCity(city)
         this.$router.push("/")
         this.keyword=""
     },
     ...mapMutations(["changeCity"])
  },
  mounted (){
     const scroll=new BScroll(this.$refs.searchContent,{mouseWheel:true,click:true,tap:true})
  }
}
</script>
<style lang="scss" scoped>
@import '~styles/iconfont.css';
@import "~styles/_parameters.scss";
  .search{
      position:relative;
      background-color:$bgColor;
      padding:.1rem;
  }
  .search-input{
      width:100%;
      border-radius:.08rem;
      padding:0 .1rem;
      height:.68rem;
      color:#666;
      text-align:center;
  }
 .search-content{
     position:fixed;
     z-index:19;
     left:0;
     top:1.72rem;
     right:0;
     bottom:0;
     width:100%;
     background-color:$bgNormal;
     color:$textDarkColor;
     overflow:hidden;
 }
 .search-item{
     background-color:#fff;
     line-height:.62rem;
     padding:0 .1rem;
 }
</style>